package module;

import entity.LocalVideoConfig;
import entity.VideoItem;
import lombok.extern.slf4j.Slf4j;
import utils.aria2.Aria2Util;
import utils.json.InitConfig;
import utils.json.VideoStateUtil;
import utils.threadpool.ThreadPoolUtil;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Aria2模块，实现将下载链接传到远程Aria2服务器功能。
 */
@Slf4j
public class Aria2 {
    private static final VideoStateUtil videoStateUtil = VideoStateUtil.getInstance();
    private static final LocalVideoConfig localVideoConfig = videoStateUtil.getLocalVideoConfig();
    private static final ScheduledExecutorService service = ThreadPoolUtil.getInstance().getTimerThreadPool();
    private static final Aria2Util aria2Util = Aria2Util.getInstance();

    public static void startAria2() {
        log.info(InitConfig.ARIA2_DELAY + "分钟后开始推送下载任务到Aria2服务器。任务执行间隔时间：" + InitConfig.PERIOD + "分钟。");
        service.scheduleAtFixedRate(new Aria2Runnable(), InitConfig.ARIA2_DELAY, InitConfig.PERIOD, TimeUnit.MINUTES);
    }

    private static class Aria2Runnable extends TimerTask {
        @Override
        public void run() {
            log.info("开始处理Aria2推送任务。。。");
            List<VideoItem> videos = localVideoConfig.getVideos();
            for (VideoItem item : videos) {
                if (!item.getIsAria2()) {
                    entity.Aria2 aria2 = aria2Util.pushByVideoItem(item);
                    item.setAria2UUID(aria2.getId());
                } else {
                    log.info("视频标题：" + item.getTitle() + "，状态：已添加到Aria2服务器。");
                }
                //每个视频处理之间间隔10秒。
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("Aria2推送任务处理完成，开始保存本地配置文件。");
            VideoStateUtil.saveConfigToFile();
        }
    }

    /**
     * 判断是否成功推送到远程服务器。
     *
     * @param UUID 服务器返回的UUID
     */
    public static void isPushSuccess(String UUID) {
        List<VideoItem> videos = localVideoConfig.getVideos();
        for (VideoItem item : videos) {
            if (UUID.equals(item.getAria2UUID())) {
                item.setIsAria2(true);
                log.info("视频标题：" + item.getTitle() + "，状态：成功添加到Aria2服务器下载队列。");
            }
        }
    }
}
